package com.polaris.live.ui.me

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.polaris.live.adapter.level.GameLevelTypeAdapter
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.databinding.FragmentMeGameBinding
import com.polaris.live.viewmodel.me.RichCharmViewModel

/**
 * 游戏等级页
 *
 * @author Created by 半仙 on 2024/4/19/019 10:26
 */
class MeGameFragment : BaseVbFragment<RichCharmViewModel, FragmentMeGameBinding>() {

    private val mGameAdapter by lazy { GameLevelTypeAdapter() }

    private val mGameType by lazy { arguments?.getInt("gameType") }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.scorePartyGame()
        mBinding.gameTypeRecycler.adapter = mGameAdapter
        mBinding.gameTypeRecycler.itemAnimator = null
        initObserver()
        initListener()
    }

    private fun initObserver() {
        mViewModel.mPartyScoreLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mBinding.gameTypeRecycler.layoutManager =
                    LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)

                val listFragments = mutableListOf<Fragment>()
                it.forEach { itemData ->
                    listFragments.add(GameLevelFragment().apply {
                        arguments = bundleOf(
                            "game" to itemData
                        )
                    })
                }
                mBinding.vpList.adapter =
                    ViewPagerAdapter(listFragments, childFragmentManager, lifecycle)

                mGameAdapter.setList(it)

                if (mGameType != null && mGameType != -1) {
                    val indexOf = it.indexOfFirst { it.gameType == mGameType }
                    if (indexOf != -1) {
                        mGameAdapter.setSelect(indexOf)
                        mBinding.vpList.setCurrentItem(indexOf, false)
                    }
                }
            })
        }
    }

    private fun initListener() {
        mGameAdapter.setOnItemClickListener { _, _, position ->
            mGameAdapter.setSelect(position)

            mBinding.vpList.setCurrentItem(position, false)
        }

        mBinding.vpList.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mGameAdapter.setSelect(position)
            }
        })
    }

}